package com.xiu.weixin.service.wx.message.image;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.baidu.aip.ocr.AipOcr;
import com.xiu.weixin.pojo.message.Message;
import com.xiu.weixin.pojo.message.TextMessage;
import com.xiu.weixin.util.Consts;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class ImageMessageService {
	private static final Logger logger = LoggerFactory.getLogger(ImageMessageService.class);

	public static Message doService(Map<String, String> reqMap) {
		// 初始化一个AipOcr
		AipOcr client = new AipOcr(Consts.APP_ID, Consts.API_KEY, Consts.SECRET_KEY);

		// 可选：设置网络连接参数
		client.setConnectionTimeoutInMillis(2000);
		client.setSocketTimeoutInMillis(60000);

		// 可选：设置代理服务器地址, http和socket二选一，或者均不设置
		// client.setHttpProxy("proxy_host", proxy_port); // 设置http代理
		// client.setSocketProxy("proxy_host", proxy_port); // 设置socket代理

		// 可选：设置log4j日志输出格式，若不设置，则使用默认配置
		// 也可以直接通过jvm启动参数设置此环境变量
		// System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties");

		// 调用接口
		String path = reqMap.get("PicUrl");
		// 本地图片
		// org.json.JSONObject res = client.basicGeneral(path, new HashMap<String,
		// String>());
		// 远程图片
		org.json.JSONObject res = client.generalUrl(path, new HashMap<String, String>());
		String json = res.toString();
		logger.info("百度AI返回图片文字识别结果：" + json);
		JSONObject jsonObject = JSONObject.fromObject(json);
		JSONArray jsonArray = jsonObject.getJSONArray("words_result");
		StringBuilder sb = new StringBuilder();
		Iterator<JSONObject> it = jsonArray.iterator();
		while (it.hasNext()) {
			JSONObject object = it.next();
			sb.append(object.getString("words"));
		}
		Message msg = new TextMessage(reqMap, sb.toString());
		return msg;
	}

}
